import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Utils} from './utils/utils';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  private casServer = 'http://cas.local.com:8080/smart-sso-server';
  private backUrl = 'http://127.0.0.1:4200';
  private appCode = 'smart-sso-server';
  private utils = new Utils();
  isCollapsed = false;

  constructor(private http: HttpClient) {

  }

  ngOnInit() {
    const urlParams = this.utils.getRequestParams();

    // 从URL获取令牌
    if (urlParams['__vt_param__'] != null) {
      localStorage.setItem('token', urlParams['__vt_param__']);
    }

    // 看本地是否有令牌
    if (localStorage.getItem('token') == null) {
      window.location.href = `${this.casServer}/login?backUrl=${this.backUrl}&appCode=${this.appCode}`;
    }

    // 调用校验API看令牌是否有效
    const token = localStorage.getItem('token');
    this.http.get(`${this.casServer}/sso/validate?token=${token}`)
      .subscribe(e => {
        if (e['result'] === false) {
          window.location.href = `${this.casServer}/login?backUrl=${this.backUrl}&appCode=${this.appCode}`;
        }
      });

  }
}
